package com.lxj.student_security.service.impl;

import com.lxj.student_security.entity.LoginParam;
import com.lxj.student_security.entity.LoginRecord;
import com.lxj.student_security.mapper.UserMapper;
import com.lxj.student_security.repository.LoginRepository;
import lombok.val;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.stereotype.Component;

import java.net.InetAddress;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

@Aspect
@Component
public class LoginAopEs {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private LoginRepository loginRepository;
    @Autowired
    private ElasticsearchRestTemplate elasticsearchRestTemplate;

    /**
     * 定义切入点
     */
    @Pointcut("execution(public * com.lxj.student_security.controller.LoginController.verify(com.lxj.student_security.entity.LoginParam))&&args(loginParam)")
    public void LoginAspect(LoginParam loginParam) {

    }

    private static int a = 1;

    @After("LoginAspect(loginParam)")
    public void storageIp(LoginParam loginParam) {
        System.out.println("我进来了");
        String username = loginParam.getUsername();
        Integer userId = userMapper.findId(username);
        String ip = getIp();
        LoginRecord login = new LoginRecord();
        login.setIp(ip);
        login.setId(a);
        login.setUserId(userId);
        login.setUsername(username);
        Date date = new Date();
        System.out.println(date);
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        String format = df.format(date);
        login.setTime(format);
        try {
            val save = loginRepository.save(login);
            System.out.println(save);
            a = ++a;
        } catch (Exception e) {
            System.out.println(e);
        }
    }

    /**
     * 获取本机ip
     */
    public String getIp() {
        InetAddress ia = null;
        try {
            ia = ia.getLocalHost();
            String localname = ia.getHostName();
            String localip = ia.getHostAddress();
            System.out.println("本机名称是：" + localname);
            System.out.println("本机的ip是 ：" + localip);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return ia.getHostAddress();
    }
}